<?php

namespace app\api\logic;

use AlibabaCloud\Client\Exception\ClientException;
use app\api\cache\MemberCache;
use app\api\consDir\CodeConst;
use app\api\consDir\ErrorConst;
use app\api\services\CodeService;
use app\common\libs\Singleton;
use app\common\utils\CommonUtil;
use app\common\utils\RedLock;

/**
 * 验证码模块
 * Class MemberLogic
 * @package app\api\logic
 */
class CodeLogic extends BaseLogic
{
    use Singleton;

    /**
     * 获取验证码
     * @param $mobile
     * @param $codeType
     * @return bool
     * @throws ClientException
     */
    public function index($phone, $codeType): bool
    {
        //锁
        if (!RedLock::getInstance()->lock('code_' . $codeType . $phone, 30)) {
            CommonUtil::throwException(ErrorConst::FREQUENT_ERROR, ErrorConst::FREQUENT_ERROR_MSG);
        }
        $code = $this->generate_code();

        CodeService::getInstance()->sendMsgAli($phone, $code['code']);

        MemberCache::setUserCode($phone, $codeType, $code['code']);

        return true;
    }

    /**
     * 获取验证码
     * @param int $length
     * @return array
     */
    public function generate_code(int $length = 4): array
    {
        return ['code' => substr(str_shuffle("012345678901234567890123456789"), 0, $length)];

    }
}